// @ts-ignore
import { stringify } from 'qs';
// @ts-ignore
import sha256 from 'crypto-js/sha256';
import isNil from './isNil';

/**
 * 格式化普通请求url
 * @param {*} pathname
 * @param {*} options
 * @param {*} downloadParams
 * url上参数&拼接，body参数转json字符串
 * sign：sha256加密的值
 * {sign, sid, stamp} shaUrl上的参数
 * eg. 加密参数例如: /appPlatform/api/appPlatform/hospitalDepartment/list?sid=26000000124393627&signKey=43cda7c350b24c3980d15982f4e77851&stamp=1610685891917&{"pageNum":1,"pageSize":10}
 * 注：匹配完整url第一个'/'及后面的字符串 url.match(/^(https?:\/\/[^\/]*)(.*)/)?.[2]
 */

function getSignKey() {
  const encryptedInfo = sessionStorage.getItem('encryptedInfo');
  try {
    if (encryptedInfo === 'true') {
      const query = localStorage.getItem('query');
      return query ? JSON.parse(query) : {};
    } else {
      const userInfo = localStorage.getItem('userInfo');
      return userInfo ? JSON.parse(userInfo) : {};
    }
  } catch {
    return {};
  }
}

function formatGatewayUrl(pathname: string, options: any, downloadParams: any = {}) {
  const { sid = '', signKey = '' } = getSignKey();
  const { data: body = {}, params } = options;
  // 处理url上的参数
  const paramData = {
    sid,
    stamp: new Date().getTime(),
  };
  const reqParams = {
    ...params,
    ...paramData,
    ...downloadParams,
    signKey,
  };

  // 处理请求参数
  const sortReqParams: Record<string, any> = {};
  Object.keys(reqParams)
      .sort()
      .forEach((item) => {
          // undefined null ''不通过，0 false通过
          const temp =
              typeof reqParams[item] === 'string'
                  ? reqParams[item].trim()
                  : reqParams[item];
  
          if (!isNil(temp) && temp !== '') {
              sortReqParams[item] = temp;
          }
      });
  
  // 处理body里面的参数
  const sortBodyParams: Record<string, any> = {};
  Object.keys(body)
      .sort()
      .forEach((item) => {
          sortBodyParams[item] = body[item];
      });

  // body为{}时的处理
  const bodyToJson =
    Object.keys(body).length > 0 ? `&${JSON.stringify(sortBodyParams)}` : '';

  const shaParams = `${pathname}?${stringify(sortReqParams, {
    encode: false,
  })}${bodyToJson}`;
  const hashDigest = sha256(shaParams).toString();
  return `${pathname}?${stringify({
    sign: hashDigest,
    ...paramData,
    ...downloadParams,
  })}`;
}

export default formatGatewayUrl;
